<template>
  <view>
    <view class="setmenu">
      <view class=" _w-max _top _left _z-index-5 _pos-fixed _top _left"
        :style="{ 'background-color': 'rgba(255, 255, 255,' + srollOpacity + ')' }">
        <view :style="{ width: '100%', height: recHeight }"></view>
        <view class="felx_c f_s_18" style="position: relative;height: 96rpx;"
          :style="{ color: 'rgb(' + srollColor + ',' + srollColor + ',' + srollColor + ')' }">
          <view @click="back" style="position: absolute;left: 24rpx;top: 24rpx;"
            :style="{ filter: 'invert(' + 1 + ')' }">
            <image style="width: 48rpx;height: 48rpx;" :src="imgs.CHEVRO" mode="" />
          </view>
          超值套餐
        </view>
        <view id="top"></view>
      </view>
      <view>
        <view :style="{ width: '100%', height: recHeight }"></view>
        <view class="felx_c h_96 f_s_18" style="position: relative;height: 96rpx;"></view>
      </view>

      <!-- 正文 -->
      <scroll-view class="nav" scroll-x="true">
        <view class="nav_item" :class="{ nav_item_active: day_num === item.day }" @click="changeTab(item.day)"
          :key="item.id" v-for="item in navList">
          {{ item.package_name }}
          <view class="active_btm"></view>
        </view>
      </scroll-view>

      <view class="box">
        <!-- 取车 -->
        <view>
          <view class="address_label">
            <view class="qcwz">取车位置</view>
            <view class="smdd" @click="visit()">
              <view class="sm" :class="{ smdd_actve: is_visit }">上门</view>
              <view class="dd" :class="{ smdd_actve: !is_visit }">到店</view>
            </view>
          </view>
          <view class="address_value">
            <view class="city_name" @click="changeCity(1, '取车城市')">
              {{ area.city_name ? area.city_name : '请选择城市' }}
              <image class="arrow_down" src="https://taxi.raxan.xyz/wechat/static/images/icon-arrow-down.png" mode="">
              </image>
            </view>
            <view class="area_name" @click="changeArea(1, '取车地点')">
              {{ area.area_name ? area.area_name : '请选择地点' }}
            </view>
          </view>
        </view>
        <!-- 还车 -->
        <view v-if="is_other_places">
          <view class="address_label">
            <view class="qcwz">还车位置</view>
            <view class="smdd" @click="visit()">
              <view class="sm" :class="{ smdd_actve: is_visit }">上门</view>
              <view class="dd" :class="{ smdd_actve: !is_visit }">到店</view>
            </view>
          </view>
          <view class="address_value">
            <view class="city_name" @click="changeCity(2, '还车城市')">
              {{ area.black_city_name ? area.black_city_name : '请选择城市' }}
              <image class="arrow_down" src="https://taxi.raxan.xyz/wechat/static/images/icon-arrow-down.png" mode="">
              </image>
            </view>
            <view class="area_name" @click="changeArea(2, '还车地点')">
              {{ area.black_area_name ? area.black_area_name : '请选择地点' }}
            </view>
          </view>
        </view>
        <!-- 时间 -->
        <view class="select-time _flex-row-mid _mar-bottom-16">
          <view class="_flex-col-mid _pad-y-10" @click="showTimePicker(0)">
            <view class="_b _font-15 _mar-bottom-5">{{ DateTime.starMon || 0 }} 月 {{ DateTime.starDay || 0 }} 日</view>
            <view class="_font-14" style="color: rgba(0,0,0,0.9)">{{ formatWeekAndTime('start') }}</view>
          </view>
          <view class="_flex-1 _flex-col-mid" style="align-self: center;">
            <view class="_font-14 _border-bottom" style="padding-bottom: 18rpx;color: rgba(0,0,0,0.9)">
              共{{ day_num }}天</view>
          </view>
          <view class="_flex-col-mid _pad-y-15" @click="showTimePicker(1)">
            <view class="_b _font-15 _mar-bottom-5">{{ DateTime.endMon || 0 }} 月 {{ DateTime.endDay || 0 }} 日</view>
            <view class="_font-14" style="color: rgba(0,0,0,0.9)">{{ formatWeekAndTime('end') }}</view>
          </view>
        </view>
        <!-- 选车 -->
        <view class="_w-max _mar-bottom-10 _text-center _font-16 ">
          <view @click="toChooseCar(DateTime)" class="_w-max theme-color-bg  _pad-y-10"
            style="border-radius: 12rpx;color: #FFFFFF;">去选车</view>
        </view>
        <view class="notice">注：部分城市指定区域可免费上门送取车</view>
      </view>
      <timePicker isStar ref="timePicker" :day="day_num" @getTime='getTime'></timePicker>
    </view>
  </view>

</template>

<script>
import timePicker from '@/pages/car_index/handler/timePicker.vue';
import { disposeTime, isCityOpen } from '@/api/car.js'
import { getPackage,getDay } from '@/api/car.js'

const IMAGES = {
  CHEVRO: 'https://taxi.raxan.xyz/wechat/static/images/store_detail/a-chevron-left.png'
}

export default {
  components: {
    timePicker
  },
  data() {
    return {
      day_num: '',
      scrollFilter: 1,
      recHeight: 0,
      srollOpacity: 0,
      srollColor: 0,
      imgs: IMAGES,
      vehModeConf: {
        is_store_take: 0, // 	是否门店自取
        is_door_take: 0, // 是否上门取车
        is_free: 0
      },
      recHeight: '',//状态栏高度
      srollOpacity: 0,// 头部导航栏透明度
      is_other_places: false, //是否异店还车
      is_visit: false,//是否上门送取车
      city_list: [],//市列表
      //省、市
      area: {
        area_id: 0,
        area_name: '',
        city_id: 0,
        city_name: '',
        latitude: 0,
        longitude: 0,
        black_area_id: 0,
        black_area_name: '',
        black_city_id: 0,
        black_city_name: '',
        black_latitude: 0,
        black_longitude: 0,
      },
      DateTime: {
        days: '1天', //两日期相差的天数
        day: 0,//天数
        hour: 0,//小时数
        starStamp: null,//取车时间（时间戳）
        endStamp: null,//还车时间（时间戳）
        starMon: null, //取车月份
        endMon: null,//还车月份
        starDay: null, //取车日
        endDay: null,//还车日
        starTime: null,//取车时间
        endTime: null,//还车时间
        end_time: '',//还车时间日期列表
        start_time: '',//取车时间日期列表
      },
      navList: []
    };
  },
  onPageScroll(e) {
    this.scrollFilter = e.scrollTop < 100 ? 1 - Math.floor(e.scrollTop / 100) : 0;
    this.srollOpacity = e.scrollTop < 100 && e.scrollTop >= 20 ? '0.' + Math.floor(e.scrollTop) : e.scrollTop < 20 && e.scrollTop >= 0 ? '0.0' + Math.floor(e.scrollTop) : e.scrollTop;
  },
 async onLoad() {
    this.getPhoneInfo();
    await this.getPackage();
    await this.getCurDate();
  },
  methods: {
    back() {
      uni.navigateBack()
    },
    changeTab(day) {
      this.day_num = day;
      this.getCurDate();
    },
   async getPackage() {
    await  getPackage().then(res => {
        this.navList = res.data;
        this.day_num = this.navList[0].day;
      })
    },
    checkVehConf(type) {
      const value = this.vehModeConf[type];
      this.vehModeConf[type] = value === 0 ? 1 : 0;
    },
    formatWeekAndTime(type) {
      const weekList = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
      const { starStamp, endStamp, starTime, endTime } = this.DateTime;
      const stamp = type === 'start' ? starStamp : endStamp;
      const date = new Date(stamp);
      const index = !stamp ? -1 : date.getDay();
      const time = (type === 'start' ? starTime : endTime) || '00:00';

      let r_week = index > -1 ? weekList[index] : '';
      const new_date = new Date();

      if (
        date.getFullYear() === new_date.getFullYear() &&
        date.getMonth() === new_date.getMonth() &&
        date.getDate() === new_date.getDate()
      ) {
        r_week = '今日'
      }

      return `${r_week}${time}`;
    },
    // 获取顶部高度信息
    getPhoneInfo() {
      let that = this;
      uni.getSystemInfo({
        success(res) {
          that.recHeight = res.statusBarHeight + 'px'; //获取手机状态栏高度
        }
      });
    },
    // 修改是否异点还车
    changeSwitch() {
      this.area = {
        area_id: 0,
        area_name: '',
        city_id: 0,
        city_name: '',
        black_area_id: 0,
        black_area_name: '',
        black_city_id: 0,
        black_city_name: '',
      }
      this.is_other_places = !this.is_other_places;
      this.is_visit = this.is_other_places;
      this.area.is_other_places = this.is_other_places;
      this.area.is_visit = this.is_visit;
    },
    visit() {
      this.is_visit = !this.is_visit;
      // this.is_other_places = this.is_visit?true:this.is_other_places;
      this.is_other_places = this.is_visit ? true : false;
      this.area = {
        area_id: 0,
        area_name: '',
        city_id: 0,
        city_name: '',
        black_area_id: 0,
        black_area_name: '',
        black_city_id: 0,
        black_city_name: '',
      }
      this.area.is_other_places = this.is_other_places;
      this.area.is_visit = this.is_visit;
    },
    //选择城市
    changeCity(type, title) {
      let that = this;
      let param = {};
      param.title = title;
      // #ifdef MP-WEIXIN
      if (this.is_visit) {
        wx.chooseLocation({
          success(res) {
            const address = res.address;
            let reg = /.+?(省|市|自治区|自治州|县|区)/g;
            let city = address.match(reg)[1];
            const name = res.name;
            const latitude = res.latitude; //纬度
            const longitude = res.longitude; //经度
            isCityOpen({ city_name: city }).then((res) => {
              if (type == 1) {// 选择取车城市、地点
                that.area.city_id = res.data.id
                that.area.city_name = city;
                that.area.area_name = name;
                that.area.latitude = latitude;
                that.area.longitude = longitude;
              } else {// 选择还车城市、地点
                that.area.black_city_id = res.data.id
                that.area.black_city_name = city;
                that.area.black_area_name = name;
                that.area.black_latitude = latitude;
                that.area.black_longitude = longitude;
              }
            }).catch((err) => {
              return uni.showToast({ title: err, icon: 'none' })
            })
          }, fail(res) {
            console.log(res)
          }
        })
        return;
      }
      //#endif
      uni.navigateTo({
        url: `/pages/car_sub/address_list/index?param=${JSON.stringify(param)}`,
        events: {
          getCity(option) {
            if (type == 1) {// 选择取车城市
              that.area.city_name = option.label;
              that.area.city_id = option.value;
              that.area.area_name = '';
              that.area.area_id = 0;
            } else {// 选择还车城市
              that.area.black_city_name = option.label;
              that.area.black_city_id = option.value;
              that.area.black_area_name = '';
              that.area.black_area_id = 0;
            }
            // uni.setStorageSync('ADDRESS',that.area)
          },
        },
      })
    },
    //选择地点
    changeArea(type, title) {
      let that = this;
      let param = {};
      param.title = title;
      // #ifdef MP-WEIXIN
      if (this.is_visit) {
        wx.chooseLocation({
          success(res) {
            const address = res.address;
            let reg = /.+?(省|市|自治区|自治州|县|区)/g;
            let city = address.match(reg)[1];
            const name = res.name;
            const latitude = res.latitude; //纬度
            const longitude = res.longitude; //经度
            isCityOpen({ city_name: city }).then((res) => {
              if (type == 1) {// 选择取车城市、地点
                that.area.city_name = city;
                that.area.area_name = name;
                that.area.area_id = 0;
                that.area.city_id = res.data.id;
                that.area.latitude = latitude;
                that.area.longitude = longitude;
              } else {// 选择还车城市、地点
                that.area.black_city_name = city;
                that.area.black_area_name = name;
                that.area.black_city_id = res.data.id;
                that.area.black_area_id = 0;
                that.area.black_latitude = latitude;
                that.area.black_longitude = longitude;
              }
              that.area.is_other_places = that.is_other_places;
              that.area.is_visit = that.is_visit;
              uni.setStorageSync('ADDRESS', that.area)
            }).catch((err) => {
              return uni.showToast({ title: err, icon: 'none' })
            })
          }
        })
        return;
      }
      //#endif
      if (type == 1) {
        if (!that.area.city_id) return uni.showToast({ title: '请选择取车城市', icon: "none" })
        param.name = that.area.city_name;
        param.id = that.area.city_id;
      } else {
        if (!that.area.black_city_id) return uni.showToast({ title: '请选择还车城市', icon: "none" })
        param.name = that.area.black_city_name;
        param.id = that.area.black_city_id;
      }
      uni.navigateTo({
        url: `/pages/car_sub/address_list/index?param=${JSON.stringify(param)}`,
        events: {
          getAddress(option) {
            if (type == 1) {// 选择取车城市
              that.area.area_name = option.title;
              that.area.area_id = option.id;
              that.area.latitude = option.latitude;
              that.area.longitude = option.longitude;
            } else {// 选择还车城市
              that.area.black_area_name = option.title;
              that.area.black_area_id = option.id;
              that.area.black_latitude = option.latitude;
              that.area.black_longitude = option.longitude;
            }
            that.area.is_other_places = that.is_other_places;
            that.area.is_visit = that.is_visit;
            uni.setStorageSync('ADDRESS', that.area)
          },
        },
      })
    },
    //展示取车、还车弹窗
    showTimePicker(type, nav_type) { // 0取车  1还车
      if(type===1)return
      this.$refs.nav_type = nav_type;
      this.$refs.timePicker.picker_modal = true;
      this.$refs.timePicker.time_type = type;
      this.$refs.timePicker.getDay(400);
      this.$refs.timePicker.calTimes();
      if (this.DateTime.start_time) {
        this.$refs.timePicker.start_time = this.DateTime.start_time;
        this.$refs.timePicker.end_time = this.DateTime.end_time;
      }
    },
    //获取取车、还车时间
    getTime(date) {
      console.log(date)
      this.DateTime.start_time = date.starTime.starTime;
      this.DateTime.end_time = date.endTime.endTime;
      this.DateTime.starDay = date.starTime.date.date;
    
      this.DateTime.starTime = date.starTime.time;
      this.DateTime.starStamp = new Date(date.starTime.date.year, (date.starTime.date.month - 1), date.starTime.date.date).getTime();
      this.DateTime.starMon = date.starTime.date.month;
      
      this.DateTime.endTime = date.endTime.time;
      this.DateTime.endDay = date.endTime.date.date;
      this.DateTime.endMon = date.endTime.date.month;
      this.DateTime.endStamp = new Date(date.endTime.date.year, (date.endTime.date.month - 1), date.endTime.date.date).getTime();
  
      let diffDate = this.happenTimeFun(this.DateTime);
      this.DateTime.days = diffDate.value;
      this.DateTime.day = diffDate.day;
      this.DateTime.hour = diffDate.hour;
      this.$refs.timePicker.picker_modal = false;
    },
    // 立即选车
    toChooseCar(param) {
      if (!this.area.city_name) return uni.showToast({ title: '请选择取车城市', icon: 'none' })
      if (!this.area.area_name) return uni.showToast({ title: '请选择取车地点', icon: 'none' })
      param.areaInfo = { ...this.area };
      param.city_id = param.black_city_id = this.area.city_id;
      param.area_id = param.black_area_id = this.area.area_id;
      param.city_name = param.black_city_name = this.area.city_name;
      param.area_name = param.black_area_name = this.area.area_name;
      param.is_other_places = this.is_other_places;
      if (this.is_other_places) {
        if (!this.area.black_city_name) return uni.showToast({ title: '请选择还车城市', icon: 'none' })
        if (!this.area.black_area_name) return uni.showToast({ title: '请选择还车地点', icon: 'none' })
        param.black_city_id = this.area.black_city_id;
        param.black_area_id = this.area.black_area_id;
        param.black_city_name = this.area.black_city_name;
        param.black_area_name = this.area.black_area_name;
      }
      const vehModeConf = this.vehModeConf;
      param = { ...param, ...vehModeConf };
      param.is_visit = this.is_visit;
      if (!this.is_visit) {
        param.black_latitude = param.take_latitude = this.area.latitude;
        param.black_longitude = param.take_longitude = this.area.longitude;
      } else {
        param.black_latitude = this.area.black_latitude ? this.area.black_latitude : '';
        param.black_longitude = this.area.black_longitude ? this.area.black_longitude : '';
        param.take_latitude = this.area.latitude ? this.area.latitude : '';
        param.take_longitude = this.area.longitude ? this.area.longitude : '';
      }

      
      disposeTime(param).then((res) => {
        uni.navigateTo({
          url: `/pages/car_sub/car_list/index?param=${JSON.stringify(param)}&date=${JSON.stringify(res.data)}&day_num=${this.day_num}`
        })
      }).catch((err) => {
        uni.showToast({ title: err, icon: 'none' })
      })
    },
    // 获取当天日期、时间
    getCurDate() {
      let date = new Date();
      let year = date.getFullYear();
      let month = date.getMonth() + 1;
      let curDay = date.getDate();
      let curHours = date.getHours();
      let curMin = date.getMinutes();
      this.DateTime.starStamp = new Date(year, (month - 1), curDay).getTime();
      this.DateTime.starMon = month < 10 ? '0' + month : month;
      this.DateTime.starDay = curDay < 10 ? '0' + curDay : curDay;
      if (curMin > 30) curHours = curHours + 1;
      this.DateTime.starTime = this.DateTime.endTime = (curHours < 10 ? '0' + curHours : curHours) + ':' + (curMin < 30 ? '30' : '00');
      let tomDate = date.setDate(date.getDate() + this.day_num); //获取1天后的 时间戳
      let tom = new Date(tomDate);
      let tomYear = tom.getFullYear();
      let tomMon = tom.getMonth() + 1;
      let tomDay = tom.getDate();
      this.DateTime.endStamp = new Date(tomYear, (tomMon - 1), tomDay).getTime();
      this.DateTime.endMon = tomMon < 10 ? '0' + tomMon : tomMon;
      this.DateTime.endDay = tomDay < 10 ? '0' + tomDay : tomDay;
    },
    // 计算用车时间
    happenTimeFun(time) {
      let star_date = new Date(time.starStamp);
      let end_date = new Date(time.endStamp);
      let star_year = star_date.getFullYear();
      let end_year = end_date.getFullYear();
      let star_month = star_date.getMonth() + 1;
      let end_month = end_date.getMonth() + 1;
      star_month = star_month < 10 ? ('0' + star_month) : star_month;
      end_month = end_month < 10 ? ('0' + end_month) : end_month;
      let star_day = star_date.getDate();
      let end_day = end_date.getDate();
      star_day = star_day < 10 ? ('0' + star_day) : star_day;
      end_day = end_day < 10 ? ('0' + end_day) : end_day;
      let star_time = star_year + '-' + star_month + '-' + star_day + ' ' + time.starTime + ':00';
      let end_time = end_year + '-' + end_month + '-' + end_day + ' ' + time.endTime + ':00';
      let star_timestamp = new Date(star_time).getTime() / 1000;
      let end_timestamp = new Date(end_time).getTime() / 1000;
      let difference = (end_timestamp - star_timestamp) / 3600;
      let day = 0;
      let hour = 0;
      let sum = difference;
      for (let i = 0; i < difference; i++) {
        if (sum >= 24) {
          sum = sum - 24;
          day++;
        } else {
          hour = sum;
          break;
        }
      }
      if (hour > 0) {
        if (day > 0) {
          return {
            value: day + '天' + hour + '小时',
            day: day,
            hour: hour
          }
        } else {
          return {
            value: hour + '小时',
            day: day,
            hour: hour
          }
        }
      } else {
        return {
          value: day + '天',
          day: day,
          hour: hour
        }
      }
    }
  },
}
</script>

<style scoped lang="scss">
.setmenu {
  height: 100vh;
  background-color: #F8F9FC;
  background-image: linear-gradient(180deg, #E7F6FE 0%, #F8F9FC 27%);

  * {
    box-sizing: border-box;
    color: rgba(0, 0, 0, 0.9);
  }

  .nav {
    height: 96rpx;
    margin-bottom: 8rpx;

    .nav_item {
      display: inline-block;
      padding: 0 22rpx;
      line-height: 96rpx;
      text-align: center;
      font-family: PingFang SC, PingFang SC;
      font-weight: 400;
      font-size: 28rpx;
      color: rgba(0, 0, 0, 0.9);

      &.nav_item_active {
        font-weight: 600;
        font-size: 28rpx;
        color: #008DFF;
        position: relative;

        .active_btm {
          position: absolute;
          bottom: 0;
          left: 0;
          right: 0;
          margin: auto;
          width: 32rpx;
          height: 6rpx;
          background: #008DFF;
          border-radius: 1998rpx;
        }
      }
    }
  }

  .box {
    margin: 0 32rpx;
    padding: 32rpx;
    background-color: #FFFFFF;
    padding-bottom: 18rpx;

    .address_label {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 24rpx;

      .qcwz {
        font-family: PingFang SC, PingFang SC;
        font-weight: 400;
        font-size: 28rpx;
        color: rgba(0, 0, 0, 0.4);
        line-height: 44rpx;
        text-align: left;
      }

      .smdd {
        display: flex;
        align-items: center;
        justify-content: center;
        background: #FFFFFF;
        border-radius: 4rpx;
        border: 1rpx solid #E7E7E7;

        .sm,
        .dd {
          font-family: PingFang SC, PingFang SC;
          font-weight: 400;
          font-size: 24rpx;
          color: rgba(0, 0, 0, 0.6);
          line-height: 40rpx;
          padding: 0 8rpx;
          text-align: center;
          flex: 1;

          &.smdd_actve {
            background: #008DFF;
            border-radius: 4rpx;
            color: #FFFFFF;
          }
        }
      }
    }

    .address_value {
      margin-bottom: 32rpx;
      padding-bottom: 24rpx;
      border-bottom: 1rpx solid #E7E7E7;
      gap: 24rpx;
      display: flex;
      align-items: center;
      justify-content: flex-start;
      overflow: hidden;

      .city_name {
        font-family: PingFang SC, PingFang SC;
        font-weight: 400;
        font-size: 28rpx;
        color: rgba(0, 0, 0, 0.9);
        line-height: 44rpx;
        display: flex;
        gap: 8rpx;
        align-items: center;

        .arrow_down {
          flex: 0 0 32rpx;
          width: 32rpx;
          height: 32rpx;
        }

        .area_name {
          flex: 1;
          overflow: hidden;
          white-space: nowrap;
          text-overflow: ellipsis;
          font-family: PingFang SC, PingFang SC;
          font-weight: 400;
          font-size: 28rpx;
          color: rgba(0, 0, 0, 0.9);
          line-height: 44rpx;
        }
      }
    }

    .select-time {
      padding: 0 40rpx;
      background: #FEFEFE;
      border-radius: 24rpx 24rpx 24rpx 24rpx;
    }

    .notice {
      margin-top: 24rpx;
      font-family: PingFang SC, PingFang SC;
      font-weight: 400;
      font-size: 24rpx;
      color: rgba(0,0,0,0.4);
      line-height: 40rpx;
      text-align: left;
    }
  }
}

.felx_c {
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
}


.f_s_18 {
  font-size: 36rpx;
}
</style>